from django.shortcuts import render
from django import http
from django.views import View
from django.core.cache import cache

from .models import Area
from meid_duo.utils.response_code import RETCODE
# Create your views here.


class AreasView(View):
    """省市区三级联动"""
    def get(self,request):
        # 获取前端传来的area_id
        area_id = request.GET.get("area_id")
        if area_id is None:  # area_id 没有则代表查询所有省份，因为省份的上级行政区id为空
            province_list = cache.get("province_list") # 尝试在缓存中查询
            if province_list is None:
                # 获取表中所有省份，根据parent_id来判断，空则为省
                province_model_list = Area.objects.filter(parent__isnull=True)
                province_list = []   # 返回前端的数据
                for province_model in province_model_list: # 遍历省
                    province_dict ={
                        "id":province_model.id,
                        'name':province_model.name
                    }
                    # {   返回数据的格式
                    #     "id": 120000,
                    #     "name": "天津市"
                    # },
                    province_list.append(province_dict) # 将数据添加到空列表中
                    # 如果没有缓存则将所有数据缓存起来，方便下次查询，减轻myql数据库压力
                cache.set("province_list",province_list,3600)
            return http.JsonResponse({"code":RETCODE.OK, "errmsg":"OK",'province_list':province_list})
        else:    # 如果area_id 有值代表要查询指定省及下级行政区,查询指定市及下级行政区
            sub_data= cache.get("sub_data%s" % area_id) # 缓存
            if sub_data is None:
                try:
                    area_model = Area.objects.get(id=area_id) # 获取该area_id的数据（可能为省，也可能为市）
                except Area.DoesNotExist:
                    return http.HttpResponseForbidden("无效id")
                else:
                    # 获取该模型类下的所有下级行政区
                    subs_model_qs = area_model.subs.all()
                    sub_list = []   # 存储行政区的下级行政区
                    for subs in subs_model_qs:
                        sub_dict = {
                            "id" : subs.id,
                            'name' : subs.name
                        }
                        sub_list.append(sub_dict)
                    sub_data = {     # 存储每一个
                        "id": area_model.id,
                        'name': area_model.name,
                        'subs': sub_list
                    }
                    # 返回响应的数据格式
                    # "sub_data": {
                    #     "id": 130000,
                    #     "name": "河北省",
                    #     "subs": [
                    #         {
                    #             "id": 130100,
                    #             "name": "石家庄市"
                    #         },

                    cache.set("sub_data%s" % area_id , sub_data,3600)
            return http.JsonResponse({"code":RETCODE.OK, "errmsg":"OK","sub_data":sub_data})

